package com.zzgele.qmzb.api.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.cnc.cloudv.bean.channel.requestBean.ChannelForbiddenRequestBean;
import com.cnc.cloudv.bean.channel.requestBean.ChannelReBrodcastRequestBean;
import com.cnc.cloudv.bean.channel.requestBean.CreateChannelRequestBean;
import com.cnc.cloudv.bean.channel.requestBean.GetChannelConfigureRequestBean;
import com.cnc.cloudv.bean.channel.responseBean.CreateChannelResponseBean;
import com.cnc.cloudv.bean.channel.responseBean.GetChannelConfigureResponseBean;
import com.cnc.cloudv.bean.channel.responseBean.PullConfigure;
import com.cnc.cloudv.bean.common.ResponseBean;
import com.cnc.cloudv.live.channelManage.ChannelManage;
import com.zzgele.qmzb.api.core.AbstractService;
import com.zzgele.qmzb.api.core.Constants;
import com.zzgele.qmzb.api.dao.RoomMapper;
import com.zzgele.qmzb.api.model.Room;
import com.zzgele.qmzb.api.model.User;
import com.zzgele.qmzb.api.service.RoomService;
import com.zzgele.qmzb.api.utils.DateUtil;
import com.zzgele.qmzb.api.utils.PageUtil;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zzgele.qmzb.api.core.Constants.PUSH_DOMAIN;


/**
 * Created by Martin on 2017/07/28.
 */
@Service(interfaceClass = RoomService.class,proxy="jdk")
@Component
@Transactional
public class RoomServiceImpl extends AbstractService<Room> implements RoomService {
    @Resource
    private RoomMapper roomMapper;

    @Resource
    ChannelManage channelManage;

    public List<HashMap> getListByDistance(Map<String, Object> map) {

        PageUtil.startPage(Integer.parseInt(map.get("page").toString()),Integer.parseInt(map.get("page_size").toString()) );
        return roomMapper.getListByDistance(map);
    }

    public int getTotalTicket(Long roomId){
       BigDecimal b=  roomMapper.getTotalTicket(roomId);
        if(b!=null)
            return b.intValue();
        return 0;
    }
    
    public int getTotalDiamond(Long login_uid,Long anchor_uid){
         BigDecimal b=roomMapper.getTotalDiamond(login_uid,anchor_uid);
        if(b!=null) {
            return b.intValue();
        }
        return 0;
    }
    public int getLivingCount(){
        return roomMapper.getLivingCount();
    
    }
    public HashMap getMyInfo(Long login_uid){
        return roomMapper.getMyInfo(login_uid);
    }

    public     Integer closeLivingRoom(String cid,String status){
        return roomMapper.closeLivingRoom(cid,status);
    }


    public int getTheLivingTicket(Long uid,Integer startTime){
        BigDecimal b=roomMapper.getTheLivingTicket(uid,startTime);
        if(b!=null)
            return b.intValue();
        return 0;
    }
    public List<HashMap> getOfficialList(){
        HashMap map1 =new HashMap();
        int a= DateUtil.getCurUnixTimeStampInt().intValue()-3600*24;
        map1.put("time", a);
        PageUtil.startPage(1, 4);
        List<HashMap> hotList =roomMapper.getOfficialList(map1);
        return  hotList;
    }

    @Override
    public ResponseBean createChannel(CreateChannelRequestBean requestBean1) {
        ResponseBean createChannel = null;
        try {
            createChannel = channelManage.createChannel(requestBean1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return createChannel;
    }

    public ResponseBean getChannelConfigure(GetChannelConfigureRequestBean requestBean) {
        ResponseBean responseBean = null;
        try {
            responseBean = channelManage.getChannelConfigure(requestBean);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseBean;
    }

    @Override
    public ResponseBean channelForbidden(ChannelForbiddenRequestBean bean) {
        ResponseBean responseBean = null;
        try {
            responseBean = channelManage.channelForbidden(bean);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseBean;
    }

    @Override
    public ResponseBean channelReBrodcast(ChannelReBrodcastRequestBean bean) {
        ResponseBean ResponseBean = null;
        try {
            ResponseBean = channelManage.channelReBrodcast(bean);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseBean;
    }

    @Override
    public List<HashMap> getLists(Map<String, Object> map) {
        PageUtil.startPage(Integer.parseInt(map.get("page").toString()),Integer.parseInt(map.get("page_size").toString()) );
        return roomMapper.getList(map);
    }

    @Override
    public Room insertData(User user, Long login_uid, String room_title, Integer room_type_id, Integer province_id,
                           Integer city_id, Double lng, Double lat, String uuid,String room_type,Long roomId) {
        CreateChannelRequestBean requestBean1 = new CreateChannelRequestBean();
        requestBean1.setChannelName(user.getId().toString());
        requestBean1.setChannelType("live");
        requestBean1.setPullProtocol("0,2");
        requestBean1.setPushDomain(PUSH_DOMAIN);
        requestBean1.setPullRate("0,1,2,3,4");
        int dbResult=-1;

        Room room = new Room();
        try {
            ResponseBean bean =this.createChannel(requestBean1);
//                ResponseBean bean = channelManage.createChannel(requestBean1);
            CreateChannelResponseBean createChannelResponseBean = (CreateChannelResponseBean) bean.getData();
            if (createChannelResponseBean != null) {
                String pullid = createChannelResponseBean.getPullId();
                //Dao
                GetChannelConfigureRequestBean requestBean = new GetChannelConfigureRequestBean();
                requestBean.setPullId(pullid);
                ResponseBean responseBean =this.getChannelConfigure(requestBean);
//                    ResponseBean responseBean = channelManage.getChannelConfigure(requestBean);
                GetChannelConfigureResponseBean channelConfigureResponseBean = (GetChannelConfigureResponseBean) responseBean.getData();
                channelConfigureResponseBean.getPushConfigureInfo();

                channelConfigureResponseBean.getPullConfigureList();
                //保存入库
                room.setTopic(room_title);
                room.setTypeId(room_type_id);
                room.setType(room_type);
                room.setProvinceId(province_id);
                room.setCityId(city_id);
                room.setLng(lng);
                room.setLat(lat);
                room.setPullid(pullid);
                room.setUid(login_uid);
                room.setCid(user.getImAccid());
                room.setCname(user.getNickName());
                room.setCtime(Long.valueOf(createChannelResponseBean.getCreateTime()));
                if (channelConfigureResponseBean.getPushConfigureInfo() != null
                        && channelConfigureResponseBean.getPushConfigureInfo().size() > 0) {
                    room.setPushUrl(channelConfigureResponseBean.getPushConfigureInfo().get(0).getPushUrl());
                    room.setPushArray(JSON.toJSONString(channelConfigureResponseBean.getPushConfigureInfo().get(0)));
                }
                if (channelConfigureResponseBean.getPullConfigureList() != null) {
                    for (PullConfigure configure : channelConfigureResponseBean.getPullConfigureList()) {
                        if ("RTMP".equals(configure.getPullProtocol())) {
                            if(configure.getPullUrlList()!=null&&configure.getPullUrlList().size()>0) {
                                room.setRtmpPullUrl(configure.getPullUrlList().get(0).getOriginPullUrl());
                                room.setRtmpPullArray(JSON.toJSONString(configure.getPullUrlList().get(0)));
                            }

                        } else if ("HLS".equals(configure.getPullProtocol())) {
                            if(configure.getPullUrlList()!=null&&configure.getPullUrlList().size()>0) {
                                room.setHlsPullUrl((configure.getPullUrlList().get(0).getOriginPullUrl()));
                                room.setHlsPullArray(JSON.toJSONString(configure.getPullUrlList().get(0)));
                            }

                        }
                    }

                }

                room.setRoomid(roomId);  //聊天室ID
                room.setPlayStatus(1);
                room.setStatus(Constants.LIVE_STATUS_OPEN); //直播开启
                room.setRoomUserCount(1);
                room.setUpdateTime(DateUtil.getCurUnixTimeStampInt());
                dbResult = roomMapper.insertSelective(room);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
//                if (dbResult != 1) {
//                    //删除直播间[频道]
//                    NeteaseLiveUtil.channelDelete(cid);
//                    logger.warn("数据异常：创建直播间失败！");
//                    return ResultGenerator.genFailResult("数据异常：创建直播间失败！");
//                }
        }

        return room;
    }

}
